package ekahau.ue.registration.server;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

import ekahau.ue.registration.RegistrationClientRequest;


/**
 * 
 * @author Kashif
 *
 * Unique player connected to the server
 * 
 */
public class UERegistrationListener extends Thread{
	
        private RegistrationClientRequest request;
        private Socket socket;
        private ObjectInputStream input;
        private ObjectOutputStream output;
        private UERegistrationServer myServer;
        private String macID;
        /**
         * Constructs a handler thread for a given socket and mark
         */
        public UERegistrationListener(Socket socket, UERegistrationServer server) {
            
        	this.socket = socket;
        	myServer = server;
            server.addClient(this);
            try {
                
            	output = new ObjectOutputStream(socket.getOutputStream());
            	input = new ObjectInputStream(socket.getInputStream());
                
            } catch (IOException e) {
                System.out.println("Player Does not exist:" + e);
            }
        }

        public void run() {
            try {


                // Repeatedly get commands from the client and process them.
                while (true) {
                	
                    Object object = input.readObject();
                    if (object instanceof RegistrationClientRequest) {
                    	
                    	RegistrationClientRequest cReq = (RegistrationClientRequest)object;  
                    	myServer.processRequest(cReq, output);
                    	macID = cReq.getUserID();
                        	
                    } 
                    
                }
                
            } catch (IOException e) {
                System.out.println("Client Connection ends: " + e);
                
            } catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
                try {
                	
                	myServer.removeClient(this);
                	myServer = null;
                	socket.close();
                } catch (IOException e) {
                	e.printStackTrace();
                }catch(Exception ex){
                	ex.printStackTrace();
                }
            }
        }
        
        /**
         * 
         */
        public RegistrationClientRequest getPlayerPosition(){
        	
        	return request;
        	
        }
        public String getMacID(){
        	return macID;
        }
        /**
         * 
         */
        public ObjectOutputStream getOutputSteam(){
        	
        	return output;
        	
        }
}


